﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.Collections;

namespace EquipSecs300
{
    public class UtilitiesFile
    {
        // 选择文件路径
        public static string ChooseFilePath(string pStartPath = null)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件夹";
            dialog.ShowNewFolderButton = true;
            dialog.SelectedPath = Directory.GetCurrentDirectory();
            if (pStartPath != null)
            {
                dialog.SelectedPath = pStartPath;
            }

            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                return dialog.SelectedPath;
            }
            return null;
        }

        /// <summary>
        /// 获取目录的当前目录文件
        /// </summary>
        /// <param name="pDir"></param>
        /// <returns></returns>
        public static List<string> GetDirAllFile(string pDir)
        {
            if (pDir == null)
            {
                return null;
            }

            try
            {
                // 遍历目录
                DirectoryInfo dir = new DirectoryInfo(pDir);
                FileInfo[] dirInfo = dir.GetFiles();
                List<string> fileList = new List<string>();

                for (int i = 0; i < dirInfo.Length; i++)
                {
                    if ((dirInfo[i].Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
                    {
                        fileList.Add(dirInfo[i].Name);
                    }
                }
                return fileList;
            }
            catch (Exception)
            {
            }
            return null;
        }

        /// <summary>
        /// 获取目录下所有文件名
        /// </summary>
        /// <param name="vDir"></param>
        /// <returns></returns>
        public static List<string> GetAllFolderName(string FileDir)
        {
            try
            {
                DirectoryInfo tDir = new DirectoryInfo(FileDir);
                List<DirectoryInfo> tDirList = tDir.GetDirectories().ToList();
                List<string> tList = new List<string>();

                for (int i = 0; i < tDirList.Count; i++)
                {
                    {
                        tList.Add(tDirList[i].Name);
                    }
                }

                return tList;
            }
            catch (Exception)
            {
            }
            return null;

        }

        public static void CopyDir(string srcPath, string aimPath)
        {
            if (string.IsNullOrEmpty(aimPath)) return;

            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加
                if (aimPath[aimPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
                {
                    aimPath += System.IO.Path.DirectorySeparatorChar;
                }
                // 判断目标目录是否存在如果不存在则新建
                if (!System.IO.Directory.Exists(aimPath))
                {
                    System.IO.Directory.CreateDirectory(aimPath);
                }
                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                // string[] fileList = Directory.GetFiles（srcPath）；
                string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);
                // 遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                    if (System.IO.Directory.Exists(file))
                    {
                        CopyDir(file, aimPath + System.IO.Path.GetFileName(file));
                    }
                    // 否则直接Copy文件
                    else
                    {
                        System.IO.File.Copy(file, aimPath + System.IO.Path.GetFileName(file), true);
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        public string GetFile(string fileName, string dirName)
        {
            DirectoryInfo dirc = new DirectoryInfo(dirName);
            foreach (FileInfo file in dirc.GetFiles())
            {
                if (file.Name.IndexOf(fileName) > -1)
                {
                    return file.FullName;
                }
            }
            foreach (DirectoryInfo dir in dirc.GetDirectories())
            {
                string rtName = GetFile(fileName, dir.FullName);
                if (rtName != null)
                {
                    return rtName;
                }
            }
            return null;
        }

        static string SearchFile(string rootPath, string searchFileName)
        {
            Queue<string> queue = new Queue<string>();
            queue.Enqueue(rootPath);

            while (queue.Count > 0)
            {
                string currentPath = queue.Dequeue();
                try
                {
                    // 获取当前路径下所有文件和子目录
                    string[] fileEntries = Directory.GetFiles(currentPath, "*.*", SearchOption.AllDirectories);
                    foreach (string fileName in fileEntries)
                    {
                        if (Path.GetFileName(fileName).Equals(searchFileName, StringComparison.OrdinalIgnoreCase))
                        {
                            return fileName;
                        }
                    }
                }
                catch (Exception ex)
                {

                }
            }
            return null;
        }

        

        /// <summary>
        /// 深度复制
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <param name="RealObject"></param>
        /// <returns></returns>
        public static T DeepCopy<T>(T RealObject)
        {
            using (Stream objectStream = new MemoryStream())
            {
                //利用 System.Runtime.Serialization序列化与反序列化完成引用对象的复制
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, RealObject);
                objectStream.Seek(0, SeekOrigin.Begin);

                return (T)formatter.Deserialize(objectStream);
            }
        }
        /// <summary>
        /// 深度复制
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <param name="RealObject"></param>
        /// <returns></returns>
        public static T2 DeepCopy2<T1,T2>(T1 RealObject)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.NullValueHandling |= NullValueHandling.Include;
            string strText = JsonConvert.SerializeObject(RealObject, Formatting.Indented, settings);
            return JsonConvert.DeserializeObject<T2>(strText);
        }

    }
}
